package org.tony.common.http;

import java.net.URL;

public final class URLUtils
{
  private static final String HTTP_PREFIX = "http://";

  public static final String getHost(String url)
  {
    try
    {
      return new URL(url).getHost();
    }
    catch (Exception e)
    {
      return null;
    }
  }

  public static final String getUrl(String requestSite, String link)
  {
    if (requestSite == null || requestSite.length() == 0)
    {
      return link;
    }
    else
    {
      if (link.startsWith("/"))
      {
        StringBuilder site = new StringBuilder(HTTP_PREFIX);
        site.append(URLUtils.getHost(requestSite));
        site.append(link);
        return site.toString();
      }
      else if (link.startsWith(HTTP_PREFIX))
      {
        return link;
      }
      else
      {
        StringBuilder site = new StringBuilder();
        String path = requestSite.substring(0, requestSite.lastIndexOf("/"));
        return site.append(path).append("/").append(link).toString();
      }
    }
  }
}
